package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.config.ThreadPoolConfig;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@RestController
@RequestMapping("api/order")
@SuppressWarnings("all")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThreadPoolExecutor executor;
    /**
     * 拆单业务
     * @param request
     * @return
     */
    @RequestMapping("/orderSplit")
    public String orderSplit(HttpServletRequest request){
        String orderId = request.getParameter("orderId");
        String wareSkuMap = request.getParameter("wareSkuMap");
        // 拆单：获取到的子订单集合
        List<OrderInfo> subOrderInfoList = orderService.orderSplit(Long.parseLong(orderId),wareSkuMap);
        // 声明一个存储map的集合
        ArrayList<Map> mapArrayList = new ArrayList<>();
        // 生成子订单集合
        for (OrderInfo orderInfo : subOrderInfoList) {
            Map map = orderService.initWareOrderMap(orderInfo);
            // 添加到集合中！
            mapArrayList.add(map);
        }

        return JSON.toJSONString(mapArrayList);
    }

    /**
     * 根据订单Id查询订单信息
     * @param orderId
     * @return
     */
    @GetMapping("inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(value = "orderId") Long orderId){
        return orderService.getOrderInfo(orderId);
    }
    /**
     * 提供我的订单信息
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("auth/{page}/{limit}")
    public Result<IPage<OrderInfo>> index(@PathVariable Long page,
                                          @PathVariable Long limit, HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        // 分页
        Page<OrderInfo> pageParam = new Page<>(page, limit);
        IPage<OrderInfo> pageModel = orderService.getPage(pageParam, userId);
        return Result.ok(pageModel);
    }
    /**
     * 秒杀提交订单，秒杀订单不需要做前置判断，直接下单
     * @param orderInfo
     * @return
     */
    @PostMapping("inner/seckill/submitOrder")
    public Long submitOrder(@RequestBody OrderInfo orderInfo) {
        Long orderId = orderService.submitOrder(orderInfo);
        return orderId;
    }
    /**
     * 提交订单
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        // 获取到用户Id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        String tradeNo = request.getParameter("tradeNo");
        //流水号验证
        boolean flag = orderService.checkTradeCode(userId, tradeNo);
        if (!flag) {
            return Result.fail().message("不能重复提交订单！");
        }
        //删除流水号
        orderService.deleteTradeNo(userId);
        // 验证库存和价格
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        //定义集合收集异步对象
        List<CompletableFuture> futureList = new ArrayList<>();
        //定义集合收集错误信息
        List<String> errorList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderDetailList)){
            for (OrderDetail orderDetail : orderDetailList) {
                //异步编排 -多线程操作
                CompletableFuture<Void> StockCompletableFuture = CompletableFuture.runAsync(new Runnable() {
                    @Override
                    public void run() {
                        // 验证库存：
                        boolean checkStock = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                        if (!checkStock) {
                            errorList.add(orderDetail.getSkuName() + "库存不足！");
//                        return Result.fail().message(orderDetail.getSkuName() + "库存不足！");
                        }
                    }
                }, executor);
                futureList.add(StockCompletableFuture);

                CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(new Runnable() {
                    @Override
                    public void run() {
                        // 验证价格：
                        BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                        if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
                            //  设置最新的价格
                            List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
                            //  写入缓存：
                            cartCheckedList.forEach(cartInfo -> {
                                redisTemplate.opsForHash().put(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX, cartInfo.getSkuId().toString(), cartInfo);
                            });
                                errorList.add(orderDetail.getSkuName() + "价格有变动！");
                            //return Result.fail().message(orderDetail.getSkuName() + "价格有变动！");
                        }
                    }
                }, executor);
                futureList.add(skuPriceCompletableFuture);
            }
        }
        //合并线程
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        //错误信息集合决定是否下单
        if(errorList.size() > 0) {
            return Result.fail().message(StringUtils.join(errorList, ","));
        }
        // 验证通过，保存订单！
        Long orderId = orderService.submitOrder(orderInfo);
        return Result.ok(orderId);
    }

    /**
     * 去结算页面
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request) {
        //获取用户地址信息
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(userId);
        //获取购物列表
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(userId);
        List<OrderDetail> detailArrayList=null;
        if (!CollectionUtils.isEmpty(cartCheckedList)){
                detailArrayList = cartCheckedList.stream().map(cartInfo -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setOrderPrice(productFeignClient.getSkuPrice(cartInfo.getSkuId()));
                orderDetail.setSkuNum(cartInfo.getSkuNum());
                return orderDetail;
            }).collect(Collectors.toList());
        }
        //获取商品数量
        int totalNum=0;
        for (OrderDetail orderDetail : detailArrayList) {
            totalNum+=orderDetail.getSkuNum();
        }
        //获取总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailArrayList);
        orderInfo.sumTotalAmount();
        //生成流水号
        String tradeNo = orderService.getTradeNo(userId);
        Map<String,Object> map=new HashMap();
        map.put("userAddressList",userAddressList);
        map.put("detailArrayList",detailArrayList);
        map.put("totalNum",totalNum);
        map.put("totalAmount",orderInfo.getTotalAmount());
        map.put("tradeNo",tradeNo);
        return Result.ok(map);
    }
}
